package com.px.lovepath.utils.network;

import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;

import android.net.Uri;

public class HttpHelper {
	public static void consumeResponse(HttpResponse httpResponse) {
		if (httpResponse == null)
			return;
		
		HttpEntity entity = httpResponse.getEntity();
		if (entity == null)
			return;
		
		InputStream contentStream = null;
		try {
			contentStream = entity.getContent();
			contentStream.close();
		} catch (Exception e) {
			
		}
		
		try {
			entity.consumeContent();
		} catch (Exception e) {
			
		}
	}
	public static String guessMediaTypeFromFileName(String fileName) {
		if (fileName == null)
			return null;
		
		int dotPos = fileName.lastIndexOf('.');
		if (dotPos >= 0 && dotPos < fileName.length() - 1) {
			String extName = fileName.substring(dotPos + 1);
			if (extName.equalsIgnoreCase("txt"))
				return "text/plain";
			if (extName.equalsIgnoreCase("epub"))
				return "application/epub+zip";
			else if (extName.equalsIgnoreCase("zip"))
				return "application/zip";
			else if (extName.equalsIgnoreCase("rar"))
				return "application/x-rar-compressed";
		}
		return null;
	}
	public static boolean hasNonAsciiChar(String chars) {
		Pattern pattern = Pattern.compile("\\p{ASCII}*");
		Matcher matcher = pattern.matcher(chars);
		return matcher.matches() == false;
	}
	public static String guessResponseCharset(HttpResponse response) {
		Header contentTypeHeader = response.getFirstHeader(HttpHeaders.CONTENT_TYPE);
		
		String charset = "utf-8";
		if (contentTypeHeader != null) {
			Pattern pattern = Pattern.compile(".*charset\\=(.*)", Pattern.CASE_INSENSITIVE);
			Matcher matcher = pattern.matcher(contentTypeHeader.getValue());
			if (matcher.matches() && matcher.groupCount() > 0) {
				String group = matcher.group(1);
				if (group != null && group.length() > 0) {
					charset = group;
				}
			}
		}
		return charset;
	}
	public static String validateResponseUri(HttpResponse response, String uri) {
		if (uri != null && hasInvalidUriChar(uri) == false)
			return uri;
		
		String charset = HttpHelper.guessResponseCharset(response);
		try {
			byte[] uriBytes = uri.getBytes("ISO-8859-1");
			String utf16Uri = new String(uriBytes, charset);
			String encodedUri = Uri.encode(utf16Uri, ":/?#[]@!$&'()*+,;=");
			
			return encodedUri;
		} catch (Exception e) {
			assert false;
			return uri;
		}
	}
	public static boolean hasInvalidUriChar(String uri) {
		Pattern validUriChars = Pattern.compile("[a-zA-Z0-9\\-\\.\\_\\~\\[\\:\\/\\?\\#\\[\\]\\@\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=\\%]+");
		return validUriChars.matcher(uri).matches() == false;
	}
}
